import React from 'react';
import { connect } from 'dva';
import { Button, Input, Modal, Select, DatePicker, Radio, InputNumber, Cascader, message, TreeSelect, TimePicker,} from 'antd';
import moment from 'moment';
import Simditor from '../../../common/PateoForm/Simditor/PateoSimditor';
import PateoUploadImage from '../../../common/PateoForm/uploadImage/PateoUploadImage';
import PateoUploadFile from '../../../common/PateoForm/uploadFile/PateoUploadFile';
import { Field } from '../../../components/Charts/Field';
import { Form } from '@ant-design/compatible';
const createForm = Form.create;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { TextArea,Search } = Input;
const { Option } = Select;
const { confirm } = Modal;
@connect(state => ({
  extendForm: state.extendForm,
}))
@createForm({
  mapPropsToFields(props) {
    const formDataEdit = Object.assign({}, props.formData);
    for (const i in formDataEdit) {
      if (i.endsWith('Date')) {
        formDataEdit[i] = Form.createFormField({ value: moment(formDataEdit[i], 'YYYY-MM-DD h:mm:ss') });
      } else if(i.endsWith('Time')){
        formDataEdit[i] = Form.createFormField({ value: moment(formDataEdit[i], 'HH:mm:ss') });
      }else {
        formDataEdit[i]= Form.createFormField({value:formDataEdit[i]});
      }
    }
    return formDataEdit;
  },
  // onValuesChange(e, values) {
  // },
})
export default class AddModal extends React.PureComponent {
  constructor(props) {
    super(props);
    this.dateFormatList = props.dateFormatList;
    this.deleteFormItemList = props.deleteFormItemList;
    this.formItems = props.formItems;
  }
  state = {
    comboboxOpetions: [],
  };
  handleOk = (e) => {
    e.preventDefault();
    const {
      form: { validateFields },
      dateFormatList,
      timeFormatList,
      deleteFormItemList,
      confirmCom,
      selectArrList } =
      this.props;
    validateFields((errors, values) => {
      if (errors) { return; }
      const newValus = { ...values, };
      if (dateFormatList) {
        dateFormatList.map((title) => {
          return newValus[title].format('YYYY-MM-DD HH:mm:ss');
        });
      }
      if (timeFormatList) {
        timeFormatList.map(title => newValus[title]?
          (newValus[title]=moment(newValus[title]).format('HH:mm:00')): (newValus[title]=undefined));
      }
      if (selectArrList) {
        selectArrList.map((title) => {
          newValus[title] = values[title].join(',');
          return newValus;
        });
      }
      const formData = Object.assign(this.props.formData, newValus);
      if (deleteFormItemList) {
        deleteFormItemList.map(i => delete formData[i]);
      }
      const { updateUrl, addUrl } = this.props;
      const url = formData.id || formData.sid ? updateUrl : addUrl;
      const { handleSubmit } = this;
      if (confirmCom) {
        const fun = {
          onOk() {
            handleSubmit(url);
          },
        };
        const confimParams = { ...confirmCom, ...fun };
        confirm(confimParams);
      } else {
        handleSubmit(url);
      }
    });
  };
  handleCombobox = (value) => {
    const { comboboxDispatchType, dispatch } = this.props;
    if (!value) {
      this.setState({ comboboxOpetions: [] });
    } else {
      dispatch({
        type: comboboxDispatchType,
        payload: { name: value },
        callback: (comboboxOpetions) => {
          this.setState({ comboboxOpetions });
        },
      });
    }
  };
  handleSubmit = (url) => {
    const { dispatch, formData, callBackFetch } = this.props;
    dispatch({
      type: formData.id || formData.sid ? 'extendForm/add' : 'extendForm/add',
      payload: { url, ...formData },
      callback: (response) => {
        if (response.code === '0') {
          message.success(formData.id || formData.sid ? '修改成功' : '新增成功');
        }
        if (callBackFetch) {
          callBackFetch();
        }
      },
    });
    this.handleCancel();
  };
  handleCancel = () => {
    const { changeVisible, form } = this.props;
    form.resetFields();
    changeVisible();
  };
  renderFormItem = () => {
    const { form: { getFieldDecorator, setFieldsValue }, formItems, modalId } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
      },
    };
    const id=modalId||'publicDiv';
    const loopFormItems = data => data.map((item) => {
      const { title, key, type, rules, require, editDisabled, initialValue, filterTreeNode, fieldsName, maxCount, maxLength} = item;
      const placeholder = `请填写${typeof (title) === 'string' ? title : ''}`;
      const options = {};
      const dateFormat = 'YYYY-MM-DD HH:mm:ss';
      const timeFormat = 'HH:mm';
      options.rules = [{
        required: require,
        message: (typeof title === 'string') ? `${title}为必填项` : '不可为空',
      }];
      if (rules && !(editDisabled && !!this.props.formData.id)) {
        options.rules = rules;
        options.validateFirst = true;
      }
      if (initialValue) {
        options.initialValue = initialValue;
      }
      const componentDecorator = getFieldDecorator(key, options);
      switch (type) {
        case 'input': {
          return (
            <FormItem
              key={key}
              {...formItemLayout}
              label={title}
              hasFeedback
            >
              {
                componentDecorator(
                  <Input
                    placeholder={placeholder}
                    disabled={editDisabled && !!this.props.formData.sid}
                    maxLength={maxLength}
                  />
                )
              }
            </FormItem>);
        }
        case 'inputSearch': {
          const handleInputSearch=(value)=>{
            const { dispatch, form, fetchUrl, payloadUrl} = this.props;
              dispatch({
                type: fetchUrl,
                payload: payloadUrl ? Object.assign(payloadUrl, value) : value,
                callback:res=>form.setFieldsValue({[fieldsName]:res})
            });
          }
          return (
            <FormItem
              key={key}
              {...formItemLayout}
              label={title}
              hasFeedback
            >
              {
                componentDecorator(
                  <Search
                    placeholder={placeholder}
                    disabled={editDisabled && !!this.props.formData.id}
                    onSearch={value=>this.props.form.setFieldsValue({[fieldsName]:value})}
                   // onSearch={value=>handleInputSearch(value)}
                    enterButton
                  />
                )
              }
            </FormItem>);
        }
        case 'radio': {
          return (
            <FormItem
              {...formItemLayout}
              label={title}
              key={key}
            > {componentDecorator(
              <RadioGroup options={item.options} />
            )}
            </FormItem>
          );
        }
        case 'datePicker': {
          return (
            <FormItem
              {...formItemLayout}
              key={key}
              label={title}
            >
              {componentDecorator(
                <DatePicker
                  showTime
                  format={dateFormat}
                  showToday
                />)
              }
            </FormItem>
          );
        }
        case 'timePicker': {
          return (
            <FormItem
              {...formItemLayout}
              key={key}
              label={title}
            >
              {componentDecorator(
                <TimePicker
                  format={timeFormat}
                />)
              }
            </FormItem>
          );
        }
        case 'numInput': {
          return (
            <FormItem
              {...formItemLayout}
              key={key}
              label={title}
            >
              {componentDecorator(
                <InputNumber
                  min={item.min}
                  max={item.max}
                />
              )
              }
            </FormItem>
          );
        }
        case 'textArea': {
          return (
            <FormItem
              {...formItemLayout}
              key={key}
              label={title}
              hasFeedback
            >
              {componentDecorator(
                <TextArea rows={4} />)
              }
            </FormItem>
          );
        }
        case 'img': {
          const onImageUploadSuccess = (formitem, url) => {
            setFieldsValue({ [key]: url });
          };
          return (
            <FormItem
              key={key}
              label={title}
              {...formItemLayout}
              hasFeedback
            >
              {componentDecorator(
                <PateoUploadImage
                  text={item.text}
                  onUploadSuccess={onImageUploadSuccess}
                  formItem={key}
                  maxCount={maxCount ? maxCount : 1}
                />
            )}
            </FormItem>
          );
        }
        case 'file': {
          return (
            <FormItem
              key={key}
              label={title}
              hasFeedback
              {...formItemLayout}
            >
              {componentDecorator(
                <PateoUploadFile
                  onFileUploadSuccess={(formitem, url) => setFieldsValue({ [key]: url })}
                  maxCount={item.maxCount}
                  formItem={key}
                />
              )}
            </FormItem>
          );
        }
        case 'select': {
          let optionsDiv;
          const { selectOptions, keyValue } = item;
          if (!!selectOptions) {
            const loopOptions = o => o.map((d) => {
              if (keyValue) {
                return <Option key={d[keyValue[0]]} value={d[keyValue[0]]}>{d[keyValue[1]]}</Option>;
              } else {
                return <Option key={d.value} value={d.value}>{d.label}</Option>;
              }
            });
            optionsDiv = loopOptions(selectOptions);
            return (
              <FormItem
                {...formItemLayout}
                key={key}
                label={title}
                hasFeedback
              >
                {componentDecorator(
                  <Select
                    placeholder="请选择"
                    showSearch
                    allowClear
                    getPopupContainer={() => document.getElementById(id)}
                  >
                    {optionsDiv}
                  </Select>
                )}
              </FormItem>
            );
          } else {
            const { mode } = item;
            return (
              <FormItem
                {...formItemLayout}
                key={key}
                label={title}
                hasFeedback
              >
                {componentDecorator(
                  <Select
                    mode={mode}
                    onChange={this.handleCombobox}
                    placeholder={placeholder}
                    getPopupContainer={() => document.getElementById(id)}
                  >
                    {
                      this.state.comboboxOpetions.map(
                        d => <Option value={d.name} key={d.sid}>{d.name}</Option>
                      )
                    }
                  </Select>
                )}
              </FormItem>
            );
          }
        }
        case 'multiSelect': {
          return (
            <FormItem
              {...formItemLayout}
              key={key}
              label={title}
              hasFeedback
            >
              {componentDecorator(
                <Select
                  placeholder="请选择"
                  mode="multiple"
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  getPopupContainer={() => document.getElementById(id)}
                >
                  {item.options.map((ite) => {
                    return <Option key={ite.value} value={ite.value}>{ite.label}</Option>;
                  })}
                </Select>
              )}
            </FormItem>
          );
        }
        case 'richText': {
          const onValueChange = (value) => {
            setFieldsValue({ [key]: value });
          };
          return (
            <FormItem key={key} label={title} {...formItemLayout} >
              {componentDecorator(
                <Simditor
                  name={key}
                  onValueChange={onValueChange}
                />)}
            </FormItem>
          );
        }
        case 'treeSelect': {
          return (
            <FormItem
              {...formItemLayout}
              key={key}
              label={title}
              hasFeedback
            >
              { componentDecorator(
                <TreeSelect
                  showSearch={filterTreeNode !== undefined}
                  filterTreeNode={filterTreeNode}
                  placeholder={item.placeholder || '请选择'}
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  getPopupContainer={() => document.getElementById(id)}
                  treeData={item.options}
                  treeDefaultExpandAll
                />
              ) }
            </FormItem>
          );
        }
        case 'cascaderTree': {
          return (
            <FormItem
              {...formItemLayout}
              label={title}
              key={key}
              hasFeedback
            >
              {componentDecorator(
                <Cascader
                  options={item.options}
                  expandTrigger="hover"
                  changeOnSelect
                  showSearch
                  placeholder="请选择"
                  displayRender={label => label[label.length - 1]}
                />
              )}
            </FormItem>
          );
        }
        default: {
          return (
            <FormItem
              {...formItemLayout}
              label={title}
              key={key}
              hasFeedback
            >
              {componentDecorator(
                <Field label={item.label} value={item.value} />
              )}
            </FormItem>
          );
        }
      }
    });
    let nodeformItems;
    if (this.formItems !== undefined) {
      nodeformItems = loopFormItems(formItems);
    }
    return nodeformItems;
  }

  render() {
    const { formData, visible, title, modalId, width} = this.props;
    const divId = modalId || 'publicDiv';
    return (
      <div>
        <Modal
          width={width}
          wrapClassName="wrapModel"
          visible={visible}
          title={title || (formData.id || formData.sid ? '修改' : '新增')}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          footer={[<Button key="back" type="ghost" size="large" onClick={this.handleCancel}> 取 消 </Button>,
            <Button key="submit" type="primary" size="large" onClick={this.handleOk}>
              提 交
            </Button>]}
        >
          <div id={divId}>
          <Form>
            {this.renderFormItem()}
          </Form>
          </div>
        </Modal>
      </div>
    );
  }
}
